import React from 'react'

import PropTypes from 'prop-types'
import classNames from 'classnames'
import { faTimes, faCircle } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import './TabList.scss'

const { dialog } = window.require('electron').remote


const TabList = ({ files, activeId, unsavedIds, onTabClick, oncloseTab }) => {

  const renderFileOperateIcon = (fileId) => {

    const CCloseIcon = classNames({
      'close-icon': true,
      'visibility': fileId === activeId ? true : false,
      'withunsaved': unsavedIds.includes(fileId) ? true : false,
    })

    const CunsavedIcon = classNames({
      'unsaved-icon': true,
      'unsaved': unsavedIds.includes(fileId) ? true : false,
      'withunsaved': unsavedIds.includes(fileId) ? true : false,
    })

    const _closeTab = (fileId) => {
      if (unsavedIds.includes(fileId)) {
        dialog.showMessageBox({
          message: `是否要保存对${fileId}的更改`,
          detail: '如果不保存，你的更改将丢失',
          type: 'warning',
          buttons: ['保存', '取消', '不保存'],
          defaultId: 0,
        }).then(res => {
          console.log('res', res);
          switch (res.response) {
            case 0:
              oncloseTab(fileId, 0)
              break;
            case 1:
              console.log('取消', 1)
              break;
            case 2:
              oncloseTab(fileId, 2)
              break;
            default:
              break;
          }
        }).catch(err => {
          console.log(err);
        })
      } else {
        oncloseTab(fileId)
      }
    }

    return <>
      <span className={CCloseIcon} onClick={(e) => { e.stopPropagation(); _closeTab(fileId) }}>
        <FontAwesomeIcon icon={faTimes} size='sm' ></FontAwesomeIcon>
      </span>
      <span className={CunsavedIcon} onClick={(e) => { e.stopPropagation(); _closeTab(fileId) }}>
        <FontAwesomeIcon icon={faCircle} size='sm' color={'#d9534f'} ></FontAwesomeIcon>
      </span>
    </>
  }

  return (
    <ul className='nav nav-pills'>{
      files.map((file, index) => {
        const fClassNames = classNames('nav-link', {
          'px-8': true,
          'active': file.id === activeId ? true : false
        })
        return <li className='nav-item' key={file.id}>
          <a className={fClassNames} href="#" onClick={(e) => { e.preventDefault(); onTabClick && onTabClick(file.id) }}>
            <span className='mr-2'>{`${file.title}.md`}</span>
            {renderFileOperateIcon(file.id)}
          </a>
        </li>
      })
    }</ul>
  )
}

TabList.propTypes = {
  files: PropTypes.array,
  activeId: PropTypes.number,
  unsavedIds: PropTypes.array,
  onTabClick: PropTypes.func,
  oncloseTab: PropTypes.func
}
TabList.defaultProps = {
  unsavedIds: [],
}

export default TabList;